package org.example.springbootwebexample.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.example.springbootwebexample.pojo.AliOSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
public class AliyunOSSUtils {

//    @Value("${aliyun.oss.endpoint}")
//    private String endpoint ; //= "https://oss-cn-beijing.aliyuncs.com";
//
//    @Value("${aliyun.oss.accessKeyId}")
//    private String accessKeyId ; //= "LTAI5tDiegtWtBmec1iiuQdp";
//
//    @Value("${aliyun.oss.accessKeySecret}")
//    private String accessKeySecret ; //= "Wy9jPH0LGhKWrQVmM9pHUt3xsG2T02";
//
//    @Value("${aliyun.oss.bucketName}")
//    private String bucketName ; //= "huangpuke";

    @Autowired
    private AliOSSProperties aliOSSProperties;

    public String upload(MultipartFile multipartFile) throws Exception {



        String originalName =  multipartFile.getOriginalFilename();
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = UUID.randomUUID().toString() +
                originalName.substring(originalName.lastIndexOf("."));



        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(aliOSSProperties.getEndpoint(),aliOSSProperties.getAccessKeyId(),aliOSSProperties.getAccessKeySecret());

        try {
            InputStream inputStream =multipartFile.getInputStream();
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(aliOSSProperties.getBucketName(), objectName, inputStream);
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return "https://" + aliOSSProperties.getBucketName() + ".oss-cn-beijing.aliyuncs.com/" + objectName;
    }

}




